<?php
/**
 * Created by PhpStorm.
 * User: mofeng
 * Date: 16/8/24
 * Time: 下午4:44
 */
/**
 * @param $url
 * @param array $form_params
 * @param array $headers
 * @param array $curl
 * @param string $cookies
 * @param array $options
 * @return mixed|\Psr\Http\Message\ResponseInterface
 */
function post($url, $form_params = [], $headers = [], $curl = [], $cookies = '', $options = [])
{
    return Guzzle::request('post', $url, array_merge($options, ['headers' => $headers, 'form_params' => $form_params, 'curl' => $curl, 'cookies' => $cookies]));
}

function postJson($url, $json = [], $options = [])
{
    return Guzzle::request('post', $url, array_merge($options, ['json' => $json]));
}

function get($url, $headers = [], $curl = [], $cookies = '', $options = [])
{
    return Guzzle::request('get', $url, array_merge($options, ['headers' => $headers, 'curl' => $curl, 'cookies' => $cookies]));
}


if (!function_exists('error')) {
    /**
     * @param $message
     * @param array $context
     * @return bool
     */
    function error($message, $context = [])
    {
        return Log::error($message, $context);
    }
}
if (!function_exists('warning')) {
    /**
     * @param $message
     * @param array $context
     * @return bool
     */
    function warning($message, $context = [])
    {
        return Log::warning($message, $context);
    }
}

function array2csv($row, $delimiter = ',', $enclosure = '"', $eol = "\n")
{
    static $fp = false;
    if ($fp === false) {
        $fp = fopen('php://temp', 'r+');
    } else {
        rewind($fp);
    }

    if (fputcsv($fp, $row, $delimiter, $enclosure) === false) {
        return false;
    }

    rewind($fp);
    $csv = fgets($fp);

    if ($eol != PHP_EOL) {
        $csv = substr($csv, 0, (0 - strlen(PHP_EOL))) . $eol;
    }

    return $csv;
}

function multiUnique($array)
{
    $return = array();
    foreach ($array as $key => $v) {
        if (!in_array($v, $return)) {
            $return[$key] = $v;
        }
    }

    return $return;
}

function authUser()
{
    return Auth::user();
}

function isIdNo($idNo)
{
    $idNo = strtoupper(strval($idNo));
    if (strlen($idNo) != 18) {
        return false;
    }
    $wi    = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    $ai    = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    $sigma = 0;
    for ($i = 0; $i < 17; $i++) {
        $sigma += ((int)$idNo{$i}) * $wi[$i];
    }

    return $ai[($sigma % 11)] == $idNo{$i};
}

function arrayLoad(&$haystack, $key, $value)
{
    $keys = array_keys(array_column($haystack, $key), $value);
    if (empty($keys)) {
        return;
    }
    $key = current($keys);
    reset($haystack);
    for ($i = 0; $i < $key; $i++) {
        next($haystack);
    }

    return current($haystack);
}

function tsv2Array(&$tsv)
{
    $tsv = explode("\n", trim($tsv));
    foreach ($tsv as $index => $item) {
        $item = explode("\t", trim($item));
        if (!$index) {
            $header = $item;
        } else {
            $items[] = array_combine($header, $item);
        }
    }

    return $items;
}

function base64_convert_encode($val, $from, $to)
{
    return math\base_convert("1" . $val, config("app.base64_convert.$from"), config("app.base64_convert.$to"));
}

function base64_convert_decode($val, $from, $to)
{
    return substr(math\base_convert($val, config("app.base64_convert.$from"), config("app.base64_convert.$to")), 1);
}

function base_convert_alt($val, $from_base, $to_base)
{
    static $gmp;
    static $bc;
    static $gmp62;
    $ratio   = 0;
    $base_10 = '';
    $result  = '';
    if ($from_base < 37) {
        $val = strtoupper($val);
    }
    if ($gmp === null) {
        $gmp = function_exists('gmp_init');
    }
    if ($gmp62 === null) {
        $gmp62 = version_compare(PHP_VERSION, '5.3.2') >= 0;
    }
    if ($gmp && ($gmp62 or ($from_base < 37 && $to_base < 37))) {
        return gmp_strval(gmp_init($val, $from_base), $to_base);
    }
    if ($bc === null) {
        $bc = function_exists('bcscale');
    }
    $range = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    if ($from_base == 10) {
        $base_10 = $val;
    } else {
        $n = strlen(($val = "$val")) - ++$ratio;
        if ($bc) {
            for ($i = $n; $i > -1; ($ratio = bcmul($ratio, $from_base)) && $i--) {
                $base_10 = bcadd($base_10, bcmul(strpos($range, $val[$i]), $ratio));
            }
        } else {
            for ($i = $n; $i > -1; ($ratio *= $from_base) && $i--) {
                $base_10 += strpos($range, $val[$i]) * $ratio;
            }
        }
    }
    if ($bc) {
        do {
            $result .= $range[bcmod($base_10, $to_base)];
        } while (($base_10 = bcdiv($base_10, $to_base)) >= 1);
    } else {
        do {
            $result .= $range[$base_10 % $to_base];
        } while (($base_10 /= $to_base) >= 1);
    }

    return strrev($to_base < 37 ? strtolower($result) : $result);
}

function md5Int2BigInt($number)
{
    $result           = [];
    $number           .= '';
    $result['string'] = substr(base_convert_alt(md5($number), 16, 62), 0, 10);
    $result['bigint'] = base_convert_alt($result['string'], 62, 10);

    return $result;
}

if (!function_exists('str_shell')) {
    /**
     * @param $str
     * @param $left
     * @param $right
     * @return bool|string
     */
    function str_shell($str, $left, $right)
    {
        if (!empty($left)) {
            if (strpos($str, $left) === false) {
                return false;
            }
            $str = substr($str, strpos($str, $left) + strlen($left));
        }
        if (!empty($right)) {
            if (strpos($str, $right) === false) {
                return false;
            }
            $str = substr($str, 0, strpos($str, $right));
        }

        return $str;
    }
}

if (!function_exists('checkKingCardAge')) {
    /**
     * 检查大王卡年龄是否符合要求
     * @param $idNum
     * @param $province
     * @param $cardType
     * @return int|mixed
     */
    function checkKingCardAge($idNum, $minAge=16,$maxAge=0)
    {
        $birthday          = substr($idNum, 6, 8);
        $agoYearsTimeStamp = \Carbon\Carbon::now()->subYear($minAge)->timestamp;
        $birthdayTimeStamp = strtotime($birthday);

        if ($agoYearsTimeStamp - $birthdayTimeStamp < 0) {
            throw new \LogicException("您的证件未满{$minAge}周岁! 请重新提交", 102);
        }

        if ($maxAge){
            $oldYearsTimeStamp = \Carbon\Carbon::now()->subYear($maxAge)->timestamp;
            if ($birthdayTimeStamp < $oldYearsTimeStamp)
                throw new \LogicException("您的证件已超{$maxAge}周岁! 请重新提交", 103);
        }

        return $minAge;
    }
}

function ding($receiver, $content, $isAll = false, $force = false)
{
    return \DingRobot::send($receiver, $content, $isAll, $force);
}

function json_pretty($json)
{
    if (is_string($json)) {
        $jsonArray = json_decode($json);
        if (false === $jsonArray) {
            return $json;
        }

        return json_encode($jsonArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    return json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

function getAreaByDistrict($city, $district)
{


}

if (!function_exists('d')) {
    /**
     * Dump the passed variables and end the script.
     *
     * @param  mixed
     * @return void
     */
    function d()
    {
        array_map(function ($x) {
            (new \Illuminate\Support\Debug\Dumper())->dump($x);
        }, func_get_args());

    }
}

function saveKvLog($key, array $values, $created_at = null)
{
    $createdTags = [];
    $updatedTags = [];
    if (!$created_at) {
        foreach ($values as $tag => $value) {
            $log = \App\KvLog::firstOrCreate(['key' => $key, 'tag' => $tag, 'value' => $value, 'is_latest' => 1]);
            if ($log->wasRecentlyCreated) {
                //新建了记录, 说明是个新键或者键值更新了
                $updatedCount = \App\KvLog::where('key', $key)->where('tag', $tag)->where('is_latest', 1)->where('id', '!=',
                    $log->id)->update(['is_latest' => 0]);
                if ($updatedCount) {
                    //键值更新了
                    $updatedTags[] = $tag;
                } else {
                    //新键
                    $createdTags[] = $tag;
                }
            }
        }
    }
    if ($created_at) {
        foreach ($values as $tag => $value) {
            if ($nextLog = \App\KvLog::where('key', $key)->where('tag', $tag)->where('created_at', '>=', $created_at)->orderBy('created_at')->first()) {
                if (\Carbon\Carbon::parse($created_at)->eq($nextLog->created_at)) {
                    if ($nextLog->value != $value) {
                        $nextLog->value = $value;
                        $nextLog->save();
                        $updatedTags[] = $tag;
                    }
                    continue;
                }

                if ($nextLog->value == $value) {
                    $nextLog->created_at = $created_at;
                    $nextLog->save();
                    continue;
                }
            }

            if ($prevLog = \App\KvLog::where('key', $key)->where('tag', $tag)->where('created_at', '<', $created_at)->orderBy('created_at', 'desc')->first()) {
                if ($prevLog->value == $value) {
                    continue;
                }
            };
            $isLatest = 0;
            if (!$nextLog) {

                $isLatest     = 1;
                $updatedCount = \App\KvLog::where('key', $key)->where('tag', $tag)->where('is_latest', 1)->update(['is_latest' => 0]);
                if ($updatedCount) {
                    //键值更新了
                    $updatedTags[] = $tag;
                } else {
                    //新键
                    $createdTags[] = $tag;
                }
            }
            \App\KvLog::Create(['key' => $key, 'tag' => $tag, 'value' => $value, 'is_latest' => $isLatest, 'created_at' => $created_at]);
        }
    }

    return ($createdTags || $updatedTags) ? ['createdTags' => $createdTags, 'updatedTags' => $updatedTags] : [];
}

function kvSet($key, $value)
{
    $createdTags = [];
    $updatedTags = [];
    $log = \App\KvSet::updateOrCreate(['key' => $key], [ 'value' => $value]);
    if ($log->wasRecentlyCreated) {
        //新建了记录, 说明是个新键或者键值更新了
        $updatedCount = \App\KvSet::where('key', $key)->where('id', '!=',
            $log->id)->first();
        if ($updatedCount) {
            //键值更新了
            $updatedTags[] = $key;
        } else {
            //新键
            $createdTags[] = $key;
        }
    }
    return ($createdTags || $updatedTags) ? ['createdTags' => $createdTags, 'updatedTags' => $updatedTags] : [];
}

function ProductService_needRealAuthBySku($sku)
{
    if (strstr($sku, 'LTDF-NMG') || strstr($sku, 'FX-LTDF-HN') || strstr($sku, 'FX-LTDF-BJ') || strstr($sku, 'JDFX-LTDF-JSYZ') || strstr($sku, 'JDFX-DXCP-ZJJH')
        || strstr($sku, 'JDLTDF-JDZ') || strstr($sku, 'JDFX-LTDF-JDZ')) return false;
    return true;
}

function is_en($str)
{
    if(preg_match("/^[a-zA-Z\s]+$/",$str)){
        return true;
    }else{
        return false;
    }
}
function permission($currentAction)
{
    $user = authUser();
    // who you are
    $currentDepartments = $user->roles()->pluck('display_name')->toArray();
    $config             = config('ding.permissions.' . $currentAction);
    $departments        = data_get($config, 'departments', []);
    // who can
    if (!isCan($departments, $currentDepartments)) {
        throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
    }
}

function permissionV2()
{
//    $uri = \Route::current()->getUri();
    $user = authUser();
    $uri = Request::path();
    if (empty($user)) {
        return 1;
    }else{
        if($user->status == config('auth.status.stop_use')){
            return 2;
        }
        if($user->status == config('auth.status.deleted')){
            return 1;
        }
    }

    $userRole = DB::table('permission_user as pu')
                ->leftJoin('permission_func as pf','pu.permission_id','=','pf.permission_id')
                ->leftJoin('function_route as fr','pf.func_id','=','fr.func_id')
                ->leftJoin('routes as r','fr.route_id','=','r.id')
                ->where('r.route','=',$uri)
                ->where('pu.user_id',$user->id)
                ->count('r.id');
    if($userRole == 0){
        return 1;
    }
    return 3;
}

function isCan(array $whoCan, array $whoYouAre)
{
    $diff = array_diff($whoCan, $whoYouAre);
    if (count($diff) < count($whoCan)) {
        return true;
    }
    return false;
}

function base642Image($base64, $path)
{
//    $base64 = substr($base64, strpos($base64, ';base64,') + strlen(';base64,'));
    if ($baseDecode = base64_decode($base64)) {
        if (file_put_contents($path, $baseDecode)) {
            return true;
        }
    }
    return false;
}

function Image2base64($file){
    if (!is_file($file)) return '';
    $image_data                               = fread(fopen($file, 'r'), filesize($file)); //data:image/jpeg;base64,
    $base64_image                             = chunk_split(base64_encode($image_data));//'data:' . $image_info['mime'] . ';base64,' .
    $base64_image = str_replace("\r\n", "", $base64_image);
    return $base64_image;
}

function fetchFileFromDir($path)
{
    $result = [];
    $handle = opendir($path);
    while (($file = readdir($handle)) !== false) {
        if ($file == '.' || $file == '..') continue;
        !is_dir($path . '/' . $file) ? $result['file'][] = $path . '/' . $file : $result['dir'][] = $path . '/' . $file;
    }
    closedir($handle);
    return $result;
}

function sign($params, $token)
{
    ksort($params);
    $stringToSign = [];
    foreach ($params as $key => $val) {
        $stringToSign[] = "$key=$val";
    }
    $stringToSign = implode('&', $stringToSign);
    return md5($stringToSign . $token);
}

function resizeImage($file, $b ,$compress = false)
{
    list($width, $height, $type, $attr) = getimagesize($file);
    switch ($type) {
        case 1:
            $img = imagecreatefromgif($file);
            break;
        case 2:
            $img = imagecreatefromjpeg($file);
            break;
        case 3:
            $img = imagecreatefrompng($file);
            break;
        default:
            $img = imagecreatefrompng($file);
            break;
    }
    $maxwidth  = $width * $b;
    $maxheight = $height * $b;
    if ($compress){
        $stand = $maxheight>$maxwidth ?$maxheight:$maxwidth;
        if ($stand > 800){
            $p = 800 / $stand;
            $maxwidth = $maxwidth * $p;
            $maxheight = $maxheight * $p;
        }
    }
    $canvas    = imagecreatetruecolor($maxwidth, $maxheight); // 创建一个真彩色图像 我把它理解为创建了一个画布

    imagecopyresampled($canvas, $img, 0, 0, 0, 0, $maxwidth, $maxheight, $width, $height);
    imagejpeg($canvas, $file, 100);
}

/*
  * 后台操作日志
  */
function addAdminLogs($params = []){
    try{
        $user = authUser();
        if(empty($user->id)){
            $params['uid'] = data_get($params,'uid',0);
        }else{
            $params['uid'] = $user->id;
        }
        $params['created_at'] = \Carbon\Carbon::now()->toDateTimeString();
        DB::table('admin_logs')->insert($params);
        $message = 'ok';
    }catch (\Exception $e){
        warning('addAdminLog', [$params, $e->getMessage()]);
        $message = $e->getMessage();
    }
    return $message;
}
/**
 * @param $file 文件名
 * @param $type image jpeg ...
 * @return bool
 */
function isFileType($file, $type)
{
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // 返回 mime 类型 FILEINFO_MIME会带上charset
    $mime  = finfo_file($finfo, $file);
    finfo_close($finfo);
    if (strpos($mime, $type) !== false) return true;
    return false;
}


function getLetter($str)
{
    $str = substr($str, 0, 3);
    if(empty($str)){return '#';}

    $fchar=ord($str{0});

    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});

   try {
       $s1=iconv('UTF-8','gb2312',$str);

       $s2=iconv('gb2312','UTF-8',$s1);
   } catch (\Exception $e) {
       return '#';
   }

    $s=$s2==$str?$s1:$str;
//
//    $s = $str;
    $asc=ord($s{0})*256+ord($s{1})-65536;

    if($asc>=-20319&&$asc<=-20284) return 'A';

    if($asc>=-20283&&$asc<=-19776) return 'B';

    if($asc>=-19775&&$asc<=-19219) return 'C';

    if($asc>=-19218&&$asc<=-18711) return 'D';

    if($asc>=-18710&&$asc<=-18527) return 'E';

    if($asc>=-18526&&$asc<=-18240) return 'F';

    if($asc>=-18239&&$asc<=-17923) return 'G';

    if($asc>=-17922&&$asc<=-17418) return 'H';

    if($asc>=-17417&&$asc<=-16475) return 'J';

    if($asc>=-16474&&$asc<=-16213) return 'K';

    if($asc>=-16212&&$asc<=-15641) return 'L';

    if($asc>=-15640&&$asc<=-15166) return 'M';

    if($asc>=-15165&&$asc<=-14923) return 'N';

    if($asc>=-14922&&$asc<=-14915) return 'O';

    if($asc>=-14914&&$asc<=-14631) return 'P';

    if($asc>=-14630&&$asc<=-14150) return 'Q';

    if($asc>=-14149&&$asc<=-14091) return 'R';

    if($asc>=-14090&&$asc<=-13319) return 'S';

    if($asc>=-13318&&$asc<=-12839) return 'T';

    if($asc>=-12838&&$asc<=-12557) return 'W';

    if($asc>=-12556&&$asc<=-11848) return 'X';

    if($asc>=-11847&&$asc<=-11056) return 'Y';

    if($asc>=-11055&&$asc<=-10247) return 'Z';

    return "#";
}

// 时间相减2021-03-31 14:16:13
function timeDiff2($lt, $gt, $isMicro=false)
{
    info('timediff2', [$lt, $gt]);
    $tmplt = explode('.', $lt);
    $tmpgt = explode('.', $gt);

    $datelt = data_get($tmplt, '0', '');
    $dategt = data_get($tmpgt, '0', '');

    $microlt = data_get($tmplt, '1', '000');
    $microgt = data_get($tmpgt, '1', '000');

    if (empty($lt) || empty($gt)) {
        return "00:00:00";
    }



    $date1 = strtotime($datelt);

    $date2 = strtotime($dategt);

//计算两个日期之间的时间差

    $diff = abs($date2 - $date1);


    if ($microgt < $microlt) {
        $diff = $diff - 1;
        $microgt += 1000;
    }

    $micdiff = abs($microgt - $microlt);

//转换时间差的格式

//    $years = floor($diff / (365*60*60*24));
//
//    $months = floor(($diff - $years * 365*60*60*24)  / (30*60*60*24));
//
//    $days = floor(($diff - $years * 365*60*60*24 -  $months*30*60*60*24)/ (60*60*24));

    $hours = substr(str_pad(floor(($diff / (60 * 60))), 2, '0', STR_PAD_LEFT), -8);

    $minutes = substr(str_pad(floor(($diff - $hours * 60 * 60) / 60), 2, '0', STR_PAD_LEFT), -8);

    $seconds = substr(str_pad(floor(($diff - $hours * 60 * 60 - $minutes * 60)), 2, '0', STR_PAD_LEFT), -8);

    $return = "$hours:$minutes:$seconds";
    if ($micdiff > 0 || $isMicro) {
        if ($micdiff < 10) {
            $return .= ".00$micdiff";
        }
        if ($micdiff < 100) {
            $return .= ".0$micdiff";
        }
        $return .= ".$micdiff";
    }
//    info('timediff2', [$lt, $gt, $return]);
    return $return ;
    return [
//        'years' => $years,
//        'months' => $months,
//        'days' => $days,
        'hours' => $hours,
        'minutes' => $minutes,
        'seconds' => $seconds,
    ];
}

// 用时相减14:16:26
function timeDiff($datelt, $dategt)
{
//    info('timediff', [$dategt, $datelt]);
    if (empty($dategt) || empty($datelt)) {
        return "00:00:00";
    }
    $data_one = explode(':',$dategt);
    $data_two = explode(':',$datelt);
    $hour = bcsub((int)$data_one['0'],(int)$data_two['0'],0);
    $min = bcsub((int)$data_one['1'],(int)$data_two['1'],0);
    $sec = bcsub((int)$data_one['2'],(int)$data_two['2'],0);

    if ($sec<0) {
        $min = bcsub($min,1,0);
        $sec = bcadd($sec,60,0);
    }

    if ($min<0) {
        $hour = bcsub($hour,1,0);
        $min = bcadd($min,60,0);
    }

    if ($hour<10 && $hour>=0) {
        $hour='0'.$hour;
    }
    if ($min<10  && $hour>=0) {
        $min='0'.$min;
    }
    if ($sec<10  && $hour>=0) {
        $sec='0'.$sec;
    }

    return $hour.":".$min.":".$sec;
}

function micSec2Time($micSec)
{
    $micSec = intval($micSec);
    $micdiff = substr($micSec, -3);

    $diff = substr($micSec, 0, -3);


//转换时间差的格式

//    $years = floor($diff / (365*60*60*24));
//
//    $months = floor(($diff - $years * 365*60*60*24)  / (30*60*60*24));
//
//    $days = floor(($diff - $years * 365*60*60*24 -  $months*30*60*60*24)/ (60*60*24));

    $hours = substr(str_pad(floor(($diff / (60 * 60))), 2, '0', STR_PAD_LEFT), -8);

    $minutes = substr(str_pad(floor(($diff - $hours * 60 * 60) / 60), 2, '0', STR_PAD_LEFT), -8);

    $seconds = substr(str_pad(floor(($diff - $hours * 60 * 60 - $minutes * 60)), 2, '0', STR_PAD_LEFT), -8);

    $return = "$hours:$minutes:$seconds";
    if ($micdiff > 0) {
        if ($micdiff < 10) {
            $return .= ".00$micdiff";
        }
        if ($micdiff < 100) {
            $return .= ".0$micdiff";
        }
        $return .= ".$micdiff";
    }
//    info('timediff2', [$lt, $gt, $return]);
    return $return ;
}

function time2Hour($time)
{
    $return = '';
    try {
        $timeArr = explode(':',$time);
        $return = bcadd(bcadd($timeArr[1] / 60, $timeArr[2] / 3600, 4), $timeArr[0], 4);
    } catch (\Exception $e) {}

    return $return;
}

function time2Min($time)
{
    $return = '';
    try {
        $timeP = explode('.', $time);
        $timeArr = explode(':',data_get($timeP, 0, ''));

        $return = bcadd(bcadd($timeArr[0] * 60, $timeArr[2] / 60, 4), $timeArr[1], 4);
    } catch (\Exception $e) {}
    return $return;
}

function time2MicSec($time)
{
    $return = '';
    try {
        $timeP = explode('.', $time);
        $timeArr = explode(':',data_get($timeP, 0, ''));

        $return = bcadd(bcadd(bcadd($timeArr[0] * 60 * 60 * 1000, $timeArr[1] * 60 * 1000, 4), $timeArr[2] * 1000, 4), data_get($timeP, 1, ''), 4);
    } catch (\Exception $e) {}
    return $return;
}

function min2peisu($time)
{
    $return = '';
    try {
        $timeArr = explode('.',$time);
        $sec = round(bcsub($time, $timeArr[0], 4) * 60, 0);
        if ($sec < 10) {
            $sec = '0'.$sec;
        }
        $return = $timeArr[0] . "'" . $sec . "\"";
    } catch (\Exception $e) {}

    return $return;
}

function peisu2min($peisu)
{
    $preg = "/^([0-9]{1,3})'([0-9]{1,2})\"$/";
    if (preg_match($preg, $peisu, $arr)) {
        return bcadd(data_get($arr, 2, 0) / 60, data_get($arr, 1, 0), 4);
    }
}

function quzheng($chengji='')
{
    if (empty($chengji)) {
        return '';
    }
    $timeArr = explode('.',$chengji);
    if (empty(data_get($timeArr, '1', '')) || data_get($timeArr, '1', '') == '000') {
        return (data_get($timeArr, '0', ''));
    } else {
        return timeAdd(data_get($timeArr, '0', ''), '00:00:01');
    }

}

function timeAdd($time_one,$time_two){
    $data_one = explode(':',$time_one);
    $data_two = explode(':',$time_two);
    $hour = bcadd((int)$data_one['0'],(int)$data_two['0'],0);
    $min = bcadd((int)$data_one['1'],(int)$data_two['1'],0);
    $sec = bcadd((int)$data_one['2'],(int)$data_two['2'],0);

    if ($sec>59) {
        $min = bcadd($min,1,0);
        $sec = bcsub($sec,60,0);
    }

    if ($min>59) {
        $hour = bcadd($hour,1,0);
        $min = bcsub($min,60,0);
    }

    if ($hour<10) {
        $hour='0'.$hour;
    }
    if ($min<10) {
        $min='0'.$min;
    }
    if ($sec<10) {
        $sec='0'.$sec;
    }

    return $hour.":".$min.":".$sec;
}

function isDateTime($time){
    $preg = '/^([12]\d\d\d)-(0?[1-9]|1[0-2])-(0?[1-9]|[12]\d|3[0-1]) ([0-1]\d|2[0-4]):([0-5]\d)(:[0-5]\d)?$/';

    return preg_match($preg,$time);
}

function getAgeByBirth($birth)
{
    if (empty($birth)) {
        return -1;
    }
    $age = strtotime($birth);
    list($y1,$m1,$d1) = explode("-", date('Y-m-d', $age));
    $now = strtotime('now');
    list($y2,$m2,$d2) = explode("-", date('Y-m-d', $now));
    $age = $y2-$y1;
    if ((int)($m2.$d2) < (int)($m1.$d1)) {
        $age -= 1;
    }
    return $age;
}
function upload2Qiniu($path, $bucket='rent-testw')
{
    info('upload2qiniu',[$path]);
    $path = preg_replace("/ /", "%20", $path);
    info('upload2qiniu1',[$path]);
    $c = new Qiniu\Auth('6qv-u0UcmzC8D0j3siOfeq_ZztQGap6YSaWfTIVE', 'RV0ioKFGqSDXiIASeDVMNCTUFGkeGkA6sxXbxgpq');

    $policy = array(
        'callbackUrl' => env('APP_URL').'/api/system/qiniu/callback',//'http://rocky.zhuopu.net:90/api/system/qiniu/callback',//
        'callbackBody' => 'fkey=$(key)&uid=' . '120',
    );

    $token = $c->uploadToken($bucket, null, 3600, $policy);

    $multipart[] = [
        'name' => 'file',
        'contents' => fopen($path, 'r')
    ];
    $multipart[] = [
        'name' => 'token',
        'contents' => $token,
    ];

    $r = \Guzzle::request('post', 'https://up-z1.qiniup.com', ['multipart' => $multipart])->getBody()->getContents();

    $j = json_decode($r);

    return data_get($j, 'data.fkey');
    $url = "https://cdn.rockysports.cn/" . data_get($j, 'data.fkey');
}

function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $EARTH_RADIUS = 6378.137;

    $lat1 = floatval($lat1);
    $lat2 = floatval($lat2);
    $lng1 = floatval($lng1);
    $lng2 = floatval($lng2);

    $radLat1 = rad($lat1);
    $radLat2 = rad($lat2);
    $a = $radLat1 - $radLat2;
    $b = rad($lng1) - rad($lng2);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 10000) / 10000;

    return $s;
}

function distance_sql($lon1,$lat1,$lon2,$lat2)
{
    $sql = "round(6378.138*2*asin(sqrt(pow(sin( ({$lat1}*pi()/180-{$lat2}*pi()/180)/2),2)+cos({$lat1}*pi()/180)*cos({$lat2}*pi()/180)* pow(sin( ({$lon1}*pi()/180-{$lon2}*pi()/180)/2),2)))*1000) ";
    return $sql;
}

function distance($lon1, $lat1, $lon2, $lat2) {
    $R = 6371393; // 地球平均半径,单位米
    $dlat = deg2rad($lat2-$lat1);
    $dlon = deg2rad($lon2-$lon1);
    $a = pow(sin($dlat/2), 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * pow(sin($dlon/2), 2);
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $d = $R * $c;
    return round($d);
}

/**
 * @param $user  //发送人
 * @param $toUserId     //接收人
 * @param $msg
 * @param $type
 */
function toWxMessage($user, $toUserId, $msg, $type, $from='order')
{
//    print_r(func_get_args());exit;
    $template_id = 'FaKGFHEjydl70jxbrON57xCcqA9s8v56dXF6a3MMlU0';

    $wechat  = new \App\Libs\Wechat\WechatService(config('payment.jueqiweilaixcx.wechat.app_id'), config('payment.jueqiweilaixcx.wechat.app_secret'));
    $access_token = $wechat->getAccessToken();
    $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;

    $uoi = \App\Api\Auth\Models\UsersOpenId::where('app_id', '=',config('payment.jueqiweilaixcx.wechat.app_id') )
        ->where('user_id', '=', $toUserId)
        ->first();
    $openId = data_get($uoi, 'open_id', '');
    if (data_get($uoi, 'notify_count', 0) > 0) {
        $uoi->decrement('notify_count');
    }
    $params['touser'] = $openId;
    $params['template_id'] = $template_id;
    $params['page'] = 'pages/views/index/index';
    if ($from == 'order') {
        $params['page'] = 'pages/views/woshifangdong/woshifangdong';
    }
    if (in_array($from, ['chat'])) {
        $params['page'] = 'pages/views/xiaoxi/xiaoxi';
    }
//        $params['weapp_template_msg'] = [];
//        $params['weapp_template_msg']['template_id'] = $template_id;
//        $params['weapp_template_msg']['page'] = '123';
//        $params['weapp_template_msg']['form_id'] = '17648';
//        $params['weapp_template_msg']['emphasis_keyword'] = 'keyword1.DATA';
//        $params['weapp_template_msg']['data'] = '17648';
//        $params['data']['first'] = [
//            'value'=>$param['first'],
//            'color'=>$color,
//        ];
    $params['data']['thing4'] = [
        'value'=>data_get($user, 'name'),
    ];
    $params['data']['thing2'] = [
        'value'=>$msg,
    ];
//    $params['data']['time3'] = [
//        'value'=>\Carbon\Carbon::now()->toDateTimeString(),
//    ];
    $params['data']['thing1'] = [
        'value'=>$type,//聊天、评论、提醒
    ];
//    $params['data']['thing5'] = [
//        'value'=>'无',
//    ];
//            print_r($params);exit;
    $res = postJson($url, $params)->getBody()->getContents();
    info('小程序发送模板消息返回', [func_get_args(), $params, $res]);

}
function isUtf8($pstr)
{
    if (preg_match("/^([" . chr(228) . "-" . chr(233) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}){1}/", $liehuo_net) == true
        || preg_match("/([" . chr(228) . "-" . chr(233) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}){1}$/", $liehuo_net) == true
        || preg_match("/([" . chr(228) . "-" . chr(233) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}[" . chr(128) . "-" . chr(191) . "]{1}){2,}/", $pstr) == true
    ) {
        return true;
    } else {
        return false;
    }
}
function is_utf8($string)
{
    return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
}